package com.paradogs.gs.modules.world.base.unit;

import com.baidu.bjf.remoting.protobuf.Any;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.paradogs.common._cfg.Cfg;
import com.paradogs.common.utils.RandomUtils;
import com.paradogs.gs.modules.WorldObject;
import com.paradogs.gs.modules.WorldSyncData;
import com.paradogs.gs.modules.inventory.InventoryMgr;
import lombok.Getter;

import java.util.Map;

/**
 * @author: yumi
 * @date: 2025/4/21  16:08
 * @Description: TODO
 */
public class WorldMonster extends WorldObject {

    @Getter
    private Cfg.WorldUnit template;
    private Runnable revertWorldCount;

    public WorldMonster(Cfg.WorldUnit template) { this(template, null); }
    public WorldMonster(Cfg.WorldUnit template, Runnable revertWorldCount) {
        this.template = template;
        this.revertWorldCount = revertWorldCount;
        load(
                -Long.valueOf(IdWorker.getId()),
                template.world(),
                template.x(),
                template.y(),
                template.hp(),
                template.hp(),
                1,
                1,
                UnitType.MONSTER
        );
    }

    @Override
    public WorldSyncData toSyncData() {
        return new WorldSyncData(
                getId(),
                template.name(),
                UnitType.MONSTER,
                template.level(),
                getHp(),
                getMaxHp(),
                getMp(),
                getMaxMp(),
                "描述1",
                "描述2"
        );
    }

    @Override
    public void onDead(WorldObject killer) {
        try {
            // 处理掉落
            handleDrop(template.drop1(), killer);
            handleDrop(template.drop2(), killer);

            leave(getWorldId(), getX(), getY());
        } finally {
            if (revertWorldCount != null) {
                revertWorldCount.run();
            }
        }
    }

    private void handleDrop(Integer[][] dropConfig, WorldObject killer) {
        Integer[] result = RandomUtils.nextWeight(dropConfig);
        int itemId = result[0];
        int count = result[1];
        int dropType = result[3];
        if (dropType == 1) {
            // 掉落地面
            WorldDrop drop = new WorldDrop(Cfg.Item.get(itemId), getWorldId(), getX(), getY(), count);
            drop.born();
        } else if (dropType == 2 && killer != null) {
            // 掉落背包
            if (killer.getUnitType() == UnitType.PLAYER) {
                WorldPlayer player = (WorldPlayer) killer;
                InventoryMgr mgr = player.getGameObject().getMgr(InventoryMgr.class);
                mgr.update(null, Map.of(itemId, count));
            }
        }
    }

}
